public class ProducerAndConsumer {
    public static void main(String[] args) {

        Tickets ticket = new Tickets(100);

        new Producer(ticket).start();
        new Consumer(ticket).start();
    }
}

class Tickets {
    int size;//票总数
    int number;//存票序号
    int i = 0;//售票序号
    boolean available = false;//是否有待售的票

    public Tickets(int size) {
        this.size = size;
    }

    public synchronized void put() {
        //同步方法，实现存票功能
        System.out.println("Producer puts ticket " + (++number));
        available = true;
    }

    public synchronized void sell() {
        //同步方法，实现售票功能
        if (available == true && i <= number) {
            System.out.println("Consumer buys ticket " + (++i));
        }
        if (i == number) {
            available = false;
        }
    }
}

class Producer extends Thread {
    Tickets ticket = null;

    public Producer(Tickets ticked) {
        this.ticket = ticked;
    }

    @Override
    public void run() {
        while (ticket.number < ticket.size) {
            ticket.put();
        }
    }
}

class Consumer extends Thread {
    Tickets tickets = null;

    public Consumer(Tickets tickets) {
        this.tickets = tickets;
    }

    @Override
    public void run() {
        while (tickets.size > tickets.i) {
            tickets.sell();
        }
    }
}